package com.hsj.busmanager.controller;

import com.hsj.busmanager.api.*;
import com.hsj.busmanager.job.PositionJob;
import com.hsj.busmanager.mapper.BusMapper;
import com.hsj.busmanager.mapper.StatusMapper;
import com.hsj.busmanager.service.*;
import com.hsj.busmanager.util.CommonUtil;
import com.hsj.busmanager.util.Page;
import com.hsj.busmanager.util.R;
import com.hsj.busmanager.util.TabelData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private NewsService newsService;

    @Autowired
    private BusSerivce busSerivce;

    @Autowired
    private CostTypeSerivce costTypeSerivce;

    @Autowired
    private OtherCostService costService;

    @Autowired
    private ButieService butieService;

    @Autowired
    private PositionSerivce positionSerivce;

    @Autowired
    private StatusMapper statusMapper;

    @Autowired
    private PositionJob positionJob;

    @Autowired
    private RentSerivce rentSerivce;

    @Autowired
    private BusMapper busMapper;

    @RequestMapping(value = "index")
    public String index(){
        return "/admin/admin_index";
    }


    @RequestMapping(value = "/info")
    public ModelAndView info(HttpServletRequest request,ModelAndView model){

        UserBean user = (UserBean)request.getSession().getAttribute("user");

        UserBean userBean = userService.getUserById(user.getId());
        model.addObject("user",userBean);
        model.setViewName("/admin/info");
        return  model;
    }


    @RequestMapping(value = "/update")
    @ResponseBody
    public R update(UserBean user){

        try {
            userService.update(user);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("更新失败");
        }

        return R.ok("修改成功！");


    }

    @RequestMapping(value = "/driver/update")
    @ResponseBody
    public R driverUpdate(UserBean user){

        try {
            if (user.getShowDriverTime() != null && user.getShowDriverTime() != "") {
                user.setDriverTime(CommonUtil.parseDate(user.getShowDriverTime(),"yyyy-MM-dd"));
            }
            userService.update(user);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("更新失败");
        }

        return R.ok("修改成功！");

    }

    @RequestMapping(value = "/notice/update")
    @ResponseBody
    public R noticeUpdate(News news){

        try {
            newsService.update(news);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("更新失败");
        }

        return R.ok("修改成功！");

    }


    /**
     * 跳转到司机管理页面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/driver/index")
    public ModelAndView driverIndex(HttpServletRequest request,ModelAndView model){

        UserBean currenUser = (UserBean) request.getSession().getAttribute("user");
        UserBean user =  userService.getUserById(currenUser.getId());
        if(user!= null && user.getType().equals("3")){
            //表示超管
            model.setViewName("/admin/driver/list");
            return  model;
        }
        model.setViewName("/no_permission");
        return  model;

    }

    /**
     * 跳转到司机管理页面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/driver/menberIndex")
    public ModelAndView menberIndex(HttpServletRequest request,ModelAndView model){

        UserBean currenUser = (UserBean) request.getSession().getAttribute("user");
        UserBean user =  userService.getUserById(currenUser.getId());
        if(user!= null && user.getType().equals("3")){
            //表示超管
            model.setViewName("/admin/driver/memberlist");
            return  model;
        }
        model.setViewName("/no_permission");
        return  model;


    }


    @RequestMapping(value = "getDriverPage")
    @ResponseBody
    public TabelData<UserBean> getDriverPage(Page page,UserBean user){
        return userService.getDriverPage(page,user);
    }

    @RequestMapping(value = "getUnCheckInfo")
    @ResponseBody
    public TabelData<CheckUser> getUnCheckInfo(Page page,CheckUser user){
        return userService.getUnCheckInfoPage(page,user);
    }


    @RequestMapping(value = "getNoticeData")
    @ResponseBody
    public TabelData<News> getNoticeData(Page page,News news){
        return newsService.getNoticePage(page,news);
    }



    @RequestMapping(value = "/driver/delete")
    @ResponseBody
    public R delete(Integer id){
        try {
            userService.deleteById(id);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("删除失败！");
        }
        return R.ok("删除成功！");
    }


    @RequestMapping(value = "/notice/delete")
    @ResponseBody
    public R noticeDelete(Integer id){
        try {
            newsService.deleteById(id);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("删除失败！");
        }
        return R.ok("删除成功！");
    }

    /**
     * 跳转到司机信息页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/driverEidt")
    public ModelAndView driverEidt(Integer id,ModelAndView model){

        UserBean user = userService.getUserById(id);

        if(user.getDriverTime()!=null){
            user.setShowDriverTime(CommonUtil.getDateByFormat(user.getDriverTime(),"yyyy-MM-dd"));
        }

        model.addObject("user",user);

        model.setViewName("/admin/driver/info");
        return  model;
    }

    /**
     * 跳转到司机信息页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/driverEidt2")
    public ModelAndView driverEidt2(Integer id,ModelAndView model){

        model.addObject("user",userService.getUserById(id));

        model.setViewName("/admin/driver/info2");
        return  model;
    }

    /**
     * 跳转到司机信息页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/noticeEidt")
    public ModelAndView noticeEidt(Integer id,ModelAndView model){

        model.addObject("notice",newsService.getById(id));

        model.setViewName("/admin/notice/info");
        return  model;
    }

    /**
     * 跳转到司机新增页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/driver/toAdd")
    public ModelAndView driverToAdd(Integer id,ModelAndView model){

        model.setViewName("/admin/driver/add");
        return  model;
    }

    /**
     * 跳转到消息新增页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/notice/toAdd")
    public ModelAndView noticeToAdd(ModelAndView model){

        model.setViewName("/admin/notice/add");
        return  model;
    }


    @RequestMapping(value = "/driver/save")
    @ResponseBody
    public R save(UserBean user){

        try {
            if(user.getShowDriverTime()!=null){
                user.setDriverTime(CommonUtil.parseDate(user.getShowDriverTime(),"yyyy-MM-dd"));
            }
            userService.insert(user);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("保存失败");
        }

        return R.ok("保存成功！");

    }

    @RequestMapping(value = "/notice/save")
    @ResponseBody
    public R save(News news,HttpServletRequest request){


        UserBean userBean = (UserBean) request.getSession().getAttribute("user");
        try {
            newsService.insert(news,userBean.getId()+"");
        }catch (Exception e){
            e.printStackTrace();
            return R.error("保存失败");
        }

        return R.ok("保存成功！");

    }

    /**
     * 跳转到审核司机信息页面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/check/list")
    public ModelAndView checkList(HttpServletRequest request,ModelAndView model){

        model.setViewName("/admin/driver/check_list");
        return  model;
    }


    /**
     * 跳转到通知管理页面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/notice/list")
    public ModelAndView noticeList(HttpServletRequest request,ModelAndView model){

        model.setViewName("/admin/notice/list");
        return  model;
    }


    /**
     * 审核信息通过
     * @param id
     * @return
     */
    @RequestMapping(value = "/driver/check")
    @ResponseBody
    public R check(Integer id){

        try {
            userService.check(id);
        }catch (Exception e){
            e.printStackTrace();
            return  R.error("审核失败");
        }

        return  R.ok("审核成功");
    }


    /**
     * 审核信息失败
     * @param id
     * @return
     */
    @RequestMapping(value = "/driver/checkFail")
    @ResponseBody
    public R check(Integer id,String reason){

        try {
            userService.checkFail(id,reason);
        }catch (Exception e){
            e.printStackTrace();
            return  R.error("更新异常!");
        }

        return  R.ok("操作成功");
    }

    /**
     * 跳转到消息中心
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/news")
    public ModelAndView news(ModelAndView model,HttpServletRequest request){

        model.setViewName("/admin/news/news");
        return model;

    }

    @RequestMapping(value = "getNews")
    @ResponseBody
    public TabelData<News> getNews(Page page,HttpServletRequest request){
        UserBean user = (UserBean) request.getSession().getAttribute("user");
        return newsService.getNewsPage(page,user.getId());
    }

    /**
     * 跳转到租金管理页面
     * @return
     */
    @RequestMapping(value = "rentIndex")
    public String rentCoseIndex(){
        return "/admin/rent/index";
    }

    /**
     * 跳转到租金管理页面
     * @return
     */
    @RequestMapping(value = "busInfoIndex")
    public String busInfoIndex(){
        return "/admin/rent/busInfoIndex";
    }

    /**
     * 跳转到车辆实时定位页面
     * @return
     */
    @RequestMapping(value = "postionIndex")
    public String postionIndex(){
        return "/admin/rent/position_index";
    }

    /**
     * 跳转到其他费用管理页面
     * @return
     */
    @RequestMapping(value = "costIndex")
    public String costIndex(){
        return "/admin/cost/index";
    }

    /**
     * 跳转到补贴管理页面
     * @return
     */
    @RequestMapping(value = "butieIndex")
    public String butieIndex(){
        return "/admin/butie/index";
    }

    /**
     * 获取出租车信息
     * @param page
     * @param bus
     * @return
     */
    @RequestMapping(value = "getBusData")
    @ResponseBody
    public TabelData<Bus> getRentCostData(Page page, Bus bus) {
        return  busSerivce.getRentCostData(page,bus);
    }

    /**
     * 获取统计信息
     * @param page
     * @return
     */
    @RequestMapping(value = "getTotalData")
    @ResponseBody
    public TabelData<Bus> getTotalData(Page page) {
        return  rentSerivce.getTotalData(page);
    }



    /**
     * 删除司机
     * @param id
     * @return
     */
    @RequestMapping(value = "deleteBus")
    @ResponseBody
    public R deleteBus(Integer id){
        //先查该车是否有主人，如果有则不允许删除
       Bus bus =  busSerivce.getBusById(id);
       if(bus.getOwner() != -1){
           return R.error("该车有所属司机，不允许删除！");
       }else {
           //删除
           try {
               busSerivce.deleteById(id);
           } catch (Exception e) {
               e.printStackTrace();
               return R.error("删除失败！");
           }
       }
       return R.ok("删除成功");
    }

    /**
     * 跳转到修改出租车信息的页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/toEdit")
    public ModelAndView toEdit(Integer id,ModelAndView model){

        model.addObject("bus",busSerivce.getBusById(id));

        model.setViewName("/admin/bus/edit");
        return  model;
    }

    /**
     * 跳转到修改出租车信息的页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/toRentEdit")
    public ModelAndView toRentEdit(Integer id,ModelAndView model){

        model.addObject("bus",busSerivce.getBusById(id));

        model.setViewName("/admin/bus/rentedit");
        return  model;
    }


    @RequestMapping(value = "getDriverList")
    @ResponseBody
    public R getDriverList(){

        List<UserBean> users = null;
        try {
             users = userService.getDriverList();
        }catch (Exception e){
            e.printStackTrace();
            return R.error("获取司机列表失败！");
        }

        return  R.ok("drivers",users);
    }


    /**
     * 更新出租车信息
     * @param bus
     * @return
     */
    @RequestMapping(value = "/busUpdate")
    @ResponseBody
    public R busUpdate(Bus bus){

        try {
            busSerivce.update(bus);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("更新失败");
        }

        return R.ok("修改成功！");

    }


    /**
     * 获取出租车信息
     * @param page
     * @param costType
     * @return
     */
    @RequestMapping(value = "getCostType")
    @ResponseBody
    public TabelData<CostType> getCostType(Page page, CostType costType) {
        return  costTypeSerivce.getCostTypePage(page,costType);
    }

    /**
     * 获取补贴信息
     * @param page
     * @param butie
     * @return
     */
    @RequestMapping(value = "getButieType")
    @ResponseBody
    public TabelData<ButieType> getButieType(Page page, ButieType butie) {
        return  butieService.getButieTypePage(page,butie);
    }


    @RequestMapping(value = "deleteCostType")
    @ResponseBody
    public R delete(String costName){
        try {
            costTypeSerivce.deleteByCostName(costName);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("禁用失败！");
        }
        return R.ok("禁用成功！");
    }


    @RequestMapping(value = "deleteButieType")
    @ResponseBody
    public R deleteButieType(String butieName){
        try {
            butieService.deleteByButieName(butieName);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("停用失败！");
        }
        return R.ok("停用成功！");
    }


    /**
     * 跳转到其他费用的页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/toCostTypeEdit")
    public ModelAndView toCostTypeEdit(String costName,ModelAndView model){

        model.addObject("cost",costTypeSerivce.getCostTypeByCostName(costName));

        model.setViewName("/admin/cost/edit");
        return  model;
    }


    /**
     * 跳转到补贴的页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/toButieTypeEdit")
    public ModelAndView toButieTypeEdit(String butieName,ModelAndView model){

        model.addObject("butieType",butieService.getButieTypeByCostName(butieName));

        model.setViewName("/admin/butie/edit");
        return  model;
    }

    /**
     * 更新其他费用信息
     * @param costType
     * @return
     */
    @RequestMapping(value = "/costTypeUpdate")
    @ResponseBody
    public R costTypeUpdate(CostType costType){

        try {
            costTypeSerivce.update(costType);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("更新失败");
        }

        return R.ok("修改成功！");

    }

    /**
     * 更新补贴种类信息
     * @param butieType
     * @return
     */
    @RequestMapping(value = "/butieTypeUpdate")
    @ResponseBody
    public R butieTypeUpdate(ButieType butieType){

        try {
            butieService.update(butieType);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("更新失败");
        }

        return R.ok("修改成功！");

    }


    /**
     * 跳转到新增其他费用的页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/costTypeToAdd")
    public ModelAndView costTypeToAdd(ModelAndView model){

        model.setViewName("/admin/cost/add");
        return  model;
    }

    /**
     * 跳转到新增其他费用的页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/butieTypeToAdd")
    public ModelAndView butieTypeToAdd(ModelAndView model){

        model.setViewName("/admin/butie/add");
        return  model;
    }


    /**
     * 保存其他费用信息
     * @param costType
     * @return
     */
    @RequestMapping(value = "/costTypeSave")
    @ResponseBody
    public R costTypeSave(CostType costType){

        try {
            costTypeSerivce.insert(costType);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("保存失败");
        }

        return R.ok("保存成功！");

    }


    /**
     * 保存补贴类型
     * @param butieType
     * @return
     */
    @RequestMapping(value = "/butieTypeSave")
    @ResponseBody
    public R butieTypeSave(ButieType butieType){

        try {
            butieService.insert(butieType);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("保存失败");
        }

        return R.ok("保存成功！");

    }

    /**
     * 跳转到租金新增页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/rentToAdd")
    public ModelAndView rentToAdd(ModelAndView model){
        model.setViewName("/admin/rent/add");
        return  model;
    }


    /**
     *  保存车辆信息
     * @param bus
     * @return
     */
    @RequestMapping(value = "/busSave")
    @ResponseBody
    public R busSave(Bus bus){

        try {
            busSerivce.insert(bus);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("保存失败");
        }

        return R.ok("保存成功！");

    }

    /**
     * 发送费用给司机
     * @param costName
     * @return
     */
    @RequestMapping(value = "sendCost")
    @ResponseBody
    public R sendCost(String costName){
        //1、获取费用信息
           CostType costType =  costTypeSerivce.getCostTypeByCostName(costName);
           //2、获取司机列表
           List<UserBean> drivers = userService.getDriverList();
           //3、发送费用
           Cost cost = null;

            if(drivers!=null && drivers.size()>0){
                for(UserBean driver:drivers){
                    cost = new Cost();
                    cost.setIsPay(0);
                    cost.setCreateTime(new Date());
                    cost.setMount(Double.valueOf(costType.getMoney()));
                    cost.setCostName(costType.getCostName());
                    cost.setUserId(driver.getId());
                    try {
                        costService.insert(cost);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    //4、通知用户
                    newsService.send("缴费通知","您收到了一笔账单，类型为："+costName+",费用为:"+costType.getMoney()+"元，请您及时缴费！",6,driver.getId());
                }
            }



            return R.ok("发送成功！");

    }

    /**
     * 发送费用给某个司机
     * @param costName
     * @return
     */
    @RequestMapping(value = "sendSingtonCost")
    @ResponseBody
    public R sendSingtonCost(String costName,Integer owner){
        //1、获取费用信息
        CostType costType =  costTypeSerivce.getCostTypeByCostName(costName);
        //3、发送费用
        Cost cost = null;

        cost = new Cost();
        cost.setIsPay(0);
        cost.setCreateTime(new Date());
        cost.setMount(Double.valueOf(costType.getMoney()));
        cost.setCostName(costType.getCostName());
        cost.setUserId(owner);
        try {
            costService.insert(cost);
        }catch (Exception e){
            e.printStackTrace();
        }
        //4、通知用户
        newsService.send("缴费通知","您收到了一笔账单，类型为："+costName+",费用为:"+costType.getMoney()+"元，请您及时缴费！",6,owner);



        return R.ok("发送成功！");

    }

    /**
     * 发补贴给司机
     * @param butieName
     * @return
     */
    @RequestMapping(value = "sendButie")
    @ResponseBody
    public R sendButie(String butieName){
        //1、获取费用信息
        ButieType butieType =  butieService.getButieTypeByCostName(butieName);
        //2、获取司机列表
        List<UserBean> drivers = userService.getDriverList();
        //3、发送费用
        Butie butie = new Butie();
        butie.setAmount(Double.valueOf(butieType.getMoney()));
        butie.setName(butieType.getButieName());
        butie.setCreatTime(new Date());
        butieService.insert(butie);

        if(drivers!=null && drivers.size()>0){
            for(UserBean driver:drivers){
                //4、通知用户
                newsService.send("补贴通知","您收到了一笔补贴，类型为："+butieName+",费用为:"+butieType.getMoney()+"元，请您注意查收！",6,driver.getId());
            }
        }

        return R.ok("发送成功！");

    }

    /**
     * 发补贴给某个司机
     * @param butieName
     * @return
     */
    @RequestMapping(value = "sendButieSington")
    @ResponseBody
    public R sendButieSington(String butieName,Integer owner){
        //1、获取费用信息
        ButieType butieType =  butieService.getButieTypeByCostName(butieName);
        //3、发送费用
        Butie butie = new Butie();
        butie.setAmount(Double.valueOf(butieType.getMoney()));
        butie.setName(butieType.getButieName());
        butie.setCreatTime(new Date());
        butieService.insert(butie);

        //4、通知用户
        newsService.send("补贴通知","您收到了一笔补贴，类型为："+butieName+",费用为:"+butieType.getMoney()+"元，请您注意查收！",6,owner);

        return R.ok("发送成功！");

    }


    /**
     * 定位车辆
     * @param model
     * @return
     */
    @RequestMapping(value = "/position")
    public ModelAndView position(ModelAndView model,Integer id){
        model.addObject("busId",id);
        model.setViewName("/admin/bus/position");
        return  model;
    }

    /**
     * 获取车辆实时坐标
     * @param position
     * @return
     */
    @RequestMapping(value = "getPositionByBusId")
    @ResponseBody
    public R getPositionByBusId(Position position){
        Position position1 = null;
        try {
             position1 =  positionSerivce.getByBusId(position.getBusId());
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok("position1",position1);
    }

    /**
     * 开启模拟定位
     * @return
     */
    @RequestMapping(value = "openPosition")
    @ResponseBody
    public R openPosition(){
        Status status = new Status();
        status.setId(1);
        status.setOpen(1);
        try {
            statusMapper.updateByPrimaryKey(status);
            positionJob.setDistance();
        }catch ( Exception e){
            e.printStackTrace();
            return  R.error("开启模拟定位失败！");
        }
        return R.ok("开启模拟定位成功！");


    }


    /**
     * 关闭模拟定位
     * @return
     */
    @RequestMapping(value = "closePosition")
    @ResponseBody
    public R closePosition(){
        Status status = new Status();
        status.setId(1);
        status.setOpen(0);
        try {
            statusMapper.updateByPrimaryKey(status);
        }catch ( Exception e){
            e.printStackTrace();
            return  R.error("关闭模拟定位失败！");
        }
        return R.ok("关闭模拟定位成功！");


    }


    /**
     * 给所有司机发送租金账单
     * @return
     */
    @RequestMapping(value = "sendRent")
    @ResponseBody
    public R sendRent(){

        //获取所有有所属司机的车辆信息
        List<Bus> buses = busSerivce.getOnwerBusList();

        //计算租金
        Rent rent = null;
        if(buses !=null && buses.size()>0){
            for(Bus bus:buses){
                //发送租金
                double rentMoney = bus.getRentMoney()*bus.getDistanceMonth();
                rent = new Rent();
                rent.setBusId(bus.getId());
                rent.setPayTime(new Date());
                rent.setIsPay(0);
                rent.setMount(rentMoney);
                rent.setUserId(bus.getOwner());
                try {
                    rentSerivce.insert(rent);
                    newsService.send("缴费通知","您收到了一笔账单，类型为："+rent.getCostType()+",费用为:"+rentMoney+"元，请您及时缴费！",6,bus.getOwner());
                    bus.setDistanceMonth(0.00);
                    busSerivce.update(bus);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        return R.ok("发送成功！");

    }


    /**
     * 跳转统计页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/rentTotal")
    public ModelAndView rentTotal(ModelAndView model,Integer id){


        model.setViewName("/admin/total/index");
        return  model;
    }


    @RequestMapping(value = "toDriverListView")
    @ResponseBody
    public ModelAndView toDriverListView(ModelAndView model,String costName){
        model.addObject("costName",costName);
        model.setViewName("/admin/driver/driverFrame");
        return  model;
    }

    @RequestMapping(value = "toDriverListView2")
    @ResponseBody
    public ModelAndView toDriverListView2(ModelAndView model,String butieName){
        model.addObject("butieName",butieName);
        model.setViewName("/admin/driver/driverFrame2");
        return  model;
    }

}
